package com.baizhi.cmfzmanager.util;


import com.baizhi.cmfzmanager.Annotation.LogAnnotation;
import com.baizhi.cmfzmanager.dao.LogDao;
import com.baizhi.cmfzmanager.entity.Admin;
import com.baizhi.cmfzmanager.entity.Log;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Configuration
@Aspect
public class LogAspect {

    private Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Autowired
    private LogDao logDao;


    @Pointcut("@annotation(com.baizhi.cmfzmanager.Annotation.LogAnnotation)")
    public void logPointcut(){}


    @After("logPointcut()")
    public void logAfter(JoinPoint joinPoint){

        Log log = new Log();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        LogAnnotation annotation = signature.getMethod().getAnnotation(LogAnnotation.class);
        String value = annotation.value();
        log.setLogContent(value);


        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpSession session = requestAttributes.getRequest().getSession();
        Admin admin= (Admin) session.getAttribute("admin");
        String adminUsername = admin.getUsername();
        log.setAdminName(adminUsername);

        log.setLogDate(new Date());

        String ipAddrByRequest = IPKit.getIpAddrByRequest(requestAttributes.getRequest());
        log.setLogIp(ipAddrByRequest);

        logDao.insert(log);
    }
}
